// pages/son/lend/book.js
const app = getApp()
const sss = require('../SHA-1/sha.js');
const totp = require('../SHA-1/totp.js');
var chosen=0;
var chosen_CH='';
var search_result=null;
var bookContent = [];
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navbar: ['中日文文献库', '西俄文文献库'],
    currentTab: 0,
    book_content: [],
    book_content2: [],
    indicatorDots: true,
  },
  back: function () {
    wx.navigateBack({
      url: '/pages/index/index'
    })
  },
  
  navbarTap: function (e) {
    this.setData({
      currentTab: e.currentTarget.dataset.idx,
    })
    chosen=e.currentTarget.dataset.idx;
  },

  formsubmit: function (e) {
    var _this=this;
    if(chosen==0){
      chosen_CH ="WHU01";
    }
    if (chosen == 1) {
      chosen_CH = "WHU09";
    }
    var a =
      wx.request({
        url: 'https://api.ziqiang.net.cn/token/', //仅为示例，并非真实的接口地址
        method: "GET",
        data: {
          sid: app.globalData.sid,
          pwd_edu: app.globalData.pwd,
          pwd_lib: app.globalData.pwd_lib,
          binding_type: 2
        },
        dataType: JSON,
        header: {
          'content-type': 'application/json' // 默认值
        },
        success: function (res) {
          wx.showToast({
            title: '登入成功',
            icon: 'success',
            duration: 2000,
          })
          var data = JSON.parse(res.data);

          app.globalData.Token = data.token;
        
          var totpSECRET_KEY = sss.getEncodeString('+.a*vD@JrLYauz(M)HA^=}sh');
          var secret_key = totp.updateOtp(totpSECRET_KEY);
          //totp.getCode(totpSECRET_KEY)
          var timestamp = Math.round(new Date().getTime() / 1000);
          var timestampstr = timestamp.toString();//获取unix时间戳字符串
          var ran = Math.ceil(Math.random() * 1000000000);
          var ranstr = ran.toString();
          var arr = new Array(3);
          arr[0] = secret_key;
          arr[1] = timestampstr;
          arr[2] = ranstr;
          arr = arr.sort();//字典序排序
          var mix = arr[0] + arr[1] + arr[2];
          var sha1 = sss.de2(mix).toString();//sha1算法
          var a =
            wx.request({
              url: 'https://api.ziqiang.net.cn/book/search/', //仅为示例，并非真实的接口地址
              method: "GET",
              data: {
                keyword:e.detail.value.Keyword,
                doc_library:chosen_CH,
              },
              dataType: JSON,
              header: {
                'content-type': 'application/json', // 默认值
                'Authorization': 'Token ' + app.globalData.Token,
                'x-zswd-signature': sha1,
                'x-zswd-timestamp': timestamp,
                'x-zswd-nonce': ran,
              },
              success: function (res) {

                var data = JSON.parse(res.data);
                search_result=data;

                
                for (let i = 0; i < search_result.length; i++) {
                  let Name = search_result[i].name+"\n";
                  let Library_name='';
                  let Author = search_result[i].author + "\n";
                  let Leftnumber=0;
                  for (let k = 0; k < search_result[i].locations.length; k++){
                    Leftnumber = parseInt(search_result[i].locations[k].total_number) - parseInt(search_result[i].locations[k].borrowed_number);
                    Library_name = Library_name+ search_result[i].locations[k].sub_library_name+"  剩余数量："+String(Leftnumber)+"\n";
                    
                  }
        
                  let Img_url = search_result[i].img_url;
                  let cache = {
                    "Name": Name,
                    'Author': Author,
                    "Library_name": Library_name,
                    "Img_url": Img_url,
                  };
                  bookContent.push(cache);
                }

                _this.setData({
                  book_content: bookContent,
                })  


              },
              Error: function (res) {
                wx.showToast({
                  title: '登入失败',
                  icon: 'cancel',
                  duration: 2000,
                })
              }
            })

        },
        Error: function (res) {
          wx.showToast({
            title: '登入失败',
            icon: 'cancel',
            duration: 2000,
          })
        }
      })


  },

  swiper_change: function (e) {
    this.setData({
      book_content2: bookContent[e.detail.current],
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      currentTab: 0,

    })
    wx.setNavigationBarTitle({
      title: '掌上武大Tim'
    })
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#00CC66',
      animation: {
        duration: 400,
        timingFunc: 'easeIn'
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})